<template>
  <div class="css-slider-viewport">
    <div ref="slider" class="css-slider-holder">
      <div
          :style="{
'--visible-cols': visibleCols,
'--col-gap': '12px',
'--col-size': `calc((100% - var(--col-gap) * (var(--visible-cols) - 1)) / var(--visible-cols))`
}"
          class="grid grid--slider slider"
      >
        <aplusmax-home-good
            v-for="(n, index) in itemsComputed"
            :id="`grid_slider_active_${index}`"
            :key="index"
            :tag="false"
        ></aplusmax-home-good>
      </div>
    </div>
  </div>
  <aplusmax-select
      :active="active"
      :count="items.length"
      :next="slideRight"
      :prev="slideLeft"
      :slide_position="slidePosition"
  ></aplusmax-select>
</template>

<script lang='ts' setup>
import {defineProps, defineEmits, defineExpose, ref, computed, onMounted, onUnmounted} from 'vue'

const slider = ref(null)
const active = ref(1)

const getVisibleCols = () => {
  if (window.innerWidth < 768) return 2
  if (window.innerWidth < 1024) return 3
  return 4
}

const visibleCols = ref(getVisibleCols())
const totalItems = 12 // 实际项目中可从API获取

const items = computed(() => {
  const pages = Math.ceil(totalItems / visibleCols.value)
  return Array.from({length: pages}, (_, i) =>
      Array.from({length: visibleCols.value}, (_, j) => i * visibleCols.value + j + 1)
  )
})

const itemsComputed = computed(() => items.value.flat())

const handleResize = () => {
  const newCols = getVisibleCols()
  if (newCols !== visibleCols.value) {
    visibleCols.value = newCols
    active.value = 1 // 重置到第一页
  }
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const slidePosition = (position: number) => {
  active.value = position
  const container = slider.value
  if (!container) return

  const targetIndex = (position - 1) * visibleCols.value
  const targetElement = document.getElementById(`grid_slider_active_${targetIndex}`)
  if (!targetElement) return

  container.scrollLeft = targetElement.offsetLeft
}

const slideLeft = () => {
  if (active.value > 1) {
    slidePosition(active.value - 1)
  }
}

const slideRight = () => {
  if (active.value < items.value.length) {
    slidePosition(active.value + 1)
  }
}
</script>

<style lang='less' scoped>
.css-slider-viewport {
  width: 100%;
}

.css-slider-holder {
  overflow: hidden;
  scroll-behavior: smooth;
  scroll-snap-type: x mandatory;
  cursor: grab;
}

.grid.grid--slider {
  display: grid;
  grid-auto-flow: column;
  grid-template-columns: repeat(var(--visible-cols), var(--col-size));
  grid-auto-columns: var(--col-size);
  grid-gap: var(--col-gap);
  transition: transform 0.5s ease;
}

.grid_slider_active {
  scroll-snap-align: start;
}
</style>